package com.song.interceptor;

import com.song.constant.JwtClaimsConstant;
import com.song.context.BaseContext;
import com.song.properties.JwtProperties;
import com.song.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Nonnull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT令牌校验拦截器
 */
@Slf4j
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired private JwtProperties jwtProperties;
    //在controller方法执行之前处理逻辑
    public boolean preHandle(@Nonnull HttpServletRequest request,@Nonnull HttpServletResponse response,@Nonnull Object  handler) {
        //1.如果拦截的方法不是具体的业务方法，则直接放行
        if(!(handler instanceof HandlerMethod)) return true;
        //2.具体的业务方法，想要继续执行,需要验证令牌的合法性

        //2.1获取令牌 管理员和用户的令牌在请求头中存储时字段名不同
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        log.info("拦截器获取的token:{}",token);
        //2.2.校验令牌
       try {
           Claims claims = JwtUtil.parseJwt(token, jwtProperties.getAdminSecretKey());
           //2.3获取用户id
           Integer empId = (Integer) claims.get(JwtClaimsConstant.EMP_ID);
           //2.4将当前登录的用户id存储到ThreadLocal中
           BaseContext.setCurrentId(empId.longValue());
           log.info("jwt令牌校验成功，员工的id：{}",BaseContext.getCurrentId());
           return true;
       } catch (Exception e) {
           //2.4校验失败，返回401
           log.info("令牌解析失败");
           response.setStatus(401);
            return false;
       }

    }
}
